
package controller;

import java.awt.Component;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import view.ImageLibraryGUI;

/**
 *
 * @author FelipeJ
 */
public class ImageGalleryController {

    ImageLibraryGUI imageLibGUI;    //which gui is it going to modify
    Component cmp;
    
    //constructor
    public ImageGalleryController(ImageLibraryGUI imageLibGUI, Component cmp){
        this.imageLibGUI=imageLibGUI;
        this.cmp=cmp;
    }
    
    public void selectImageImport(){
        
        selectImageToImport();
        
    }
    
    //this methods allows the user to choose a file image to be copied into a predefined path (our system library)
    private String selectImageToImport(){
        
        String answer="";
        
        //open the file chooser in a predifined directory
        //JFileChooser fileChooser = new JFileChooser(new File(System.getProperty("user.dir")+"/src/savedTestFiles/"));
        JFileChooser fileChooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("IMAGES: jpeg, jpg, gif, png", "jpeg","jpg" ,"gif","png"); //use this to check later if the file is accepted filter.accept(filepath)
        fileChooser.setFileFilter(filter);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setMultiSelectionEnabled(false);

        // Show the dialog; wait until dialog is closed
        int result = fileChooser.showOpenDialog(cmp);

        // Determine which button was clicked to close the dialog
        switch (result) {
            case JFileChooser.APPROVE_OPTION:
                // Approve (Open or Save) was clicked
                
                //check if the file is of an accepted type (defined by the filter)
                File filePath = fileChooser.getSelectedFile(); //originl File  (path)
                if(filter.accept(filePath)){
                    answer =copyToLibrary(filePath);                           //send filePath to this method, where the file will be copied, the method returns name of file
                }
                else{
                    answer="&FileNotValid&";
                    JOptionPane.showMessageDialog(cmp, "The selected file is not valid !");
                }
                 break;
                
            case JFileChooser.CANCEL_OPTION:
             // Cancel or the close-dialog icon was clicked
                 answer="&Cancel&";
                 break;
            case JFileChooser.ERROR_OPTION:
             // The selection process did not complete successfully
                 answer="&Error&";
                 break;
        }

        return answer;
  
    }
    /////////////
    
    
    //copy the selected file by the user and copies it in the system folders //if file already exists it prompt question again
    //returns the name of the file created
    private String copyToLibrary(File filePath){
        
        String fileOriginalComplete = filePath.getName();                       //original file (name+extension)

        String fileOriginalName;
        String fileOriginalExt;
        
        //get name and extension of file in separate strings
        int mid = fileOriginalComplete.lastIndexOf(".");
        fileOriginalName = fileOriginalComplete.substring(0, mid);
        fileOriginalExt = fileOriginalComplete.substring(mid + 1, fileOriginalComplete.length()); 
        
        String fileGiven="" ;                                                   //name given by user
        
        boolean copyOK=false;   //this boolean flag represents if the file was copy ok. if name already exixst its not ok
        
        //ask user for name and copy into system default directory. do this until the user enters a non-existing name
        while(!copyOK){
            fileGiven =(String) JOptionPane.showInputDialog(cmp, "Please give the imported image file a name:", "Image Import", JOptionPane.INFORMATION_MESSAGE, null,null , fileOriginalName);
            File filePathDestination = new File(System.getProperty("user.dir") + "/src/userImages/" + fileGiven+"."+fileOriginalExt); //destination where the file is going to be copied
            
            //copy file, if exception catch is because file already exists
            try {
                Files.copy(filePath.toPath(),filePathDestination.toPath());
                copyOK=true;
            } catch (IOException ex) {
                copyOK=false;
            }
            if (!copyOK){  
                JOptionPane.showMessageDialog(cmp, "That name already exists, please enter a new one !");            
            }
        }
        
        return (fileGiven+"."+fileOriginalExt); //returns name of new file including extension
    }
    ////////////
    
    public void deleteImage(String imageNameExt){
            
        String imageString=System.getProperty("user.dir")+"/src/userImages/"+imageNameExt;
        File imageFile = new File(imageString);
        try {
            Files.delete(imageFile.toPath());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(cmp, "The image could not be deleted!");
        }
    }
    
    
    //this method updates the list of images
    public void updateImageList(){
        
        File file = new File(System.getProperty("user.dir")+"/src/userImages/");
        File[] fileList = file.listFiles();
        String tempFile;
        DefaultListModel listModel = new DefaultListModel();
        
        for(File f : fileList){
            listModel.addElement(f.getName());
        }
        imageLibGUI.lstImages.setModel(listModel);
    }
    
    
    
    //this method updates the image label
    public void updateImageLabel() {

        String image;
        
        //check if the user did select an option from the list
        if (imageLibGUI.lstImages.getSelectedIndex() >= 0) {
            
            image=System.getProperty("user.dir")+"/src/userImages/";
            image+=imageLibGUI.lstImages.getSelectedValue().toString();
            ImageIcon imageIcon = new ImageIcon(image);
            imageLibGUI.lblImage.setIcon(imageIcon);
            imageLibGUI.lblImage.setText("");
            
        } else {
            imageLibGUI.lblImage.setText("                No image selected !");
            imageLibGUI.lblImage.setIcon(null);
        }

        
    }    
    
    //replaces a substring in a string 
    public static String replace(String str, String pattern, String replace) {
        
        int s = 0;
        int e = 0;
        StringBuffer result = new StringBuffer();

        while ((e = str.indexOf(pattern, s)) >= 0) {
            result.append(str.substring(s, e));
            result.append(replace);
            s = e + pattern.length();
        }
        result.append(str.substring(s));
        return result.toString();
}

    public static void main(String[] args) {
        // TODO code application logic here
    }
}
